package com.csinc.generate.onekey;

import com.csinc.generate.core.CodeGenModel;
import com.csinc.generate.core.CodeGenUtil;
import com.csinc.generate.core.constant.GenCoreConstant;
import com.csinc.generate.core.utils.io.FileUtils;
import com.csinc.generate.core.utils.io.ResourceUtils;
import com.csinc.generate.core.base.model.GenerationEntity;
import com.csinc.generate.core.base.model.TemplateFileModel;
import com.csinc.generate.core.base.model.TemplateModel;
import com.csinc.generate.core.util.NameUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Create By 郭金宝 on 2018/7/23.<br>
 */
@Slf4j
public class OneKeyProject {

    private static String localPath = "D:\\source\\csinc.generate\\generate-template";
    private static List<TemplateModel> templateList = new ArrayList<>();
    private static CodeGenModel codeGenModel = new CodeGenModel();
    private static List<String> outFileList = new ArrayList<String>();
    public static void main(String[] args) throws IOException {
        String tableName = "a_admin";//表名
        codeGenModel.setDbName("kbg_admin_dev");
        codeGenModel.setDbType(GenCoreConstant.MYSQL8);
        codeGenModel.setTableName(tableName);
        codeGenModel.setUrl("jdbc:mysql://localhost:3306/kbg_admin_dev?useSSL=true&serverTimezone=GMT");
        codeGenModel.setUsername("root");
        codeGenModel.setPasswd("kingboy");
        codeGenModel.setParseType(GenCoreConstant.BEETL);
        //设置包信息 基本都是默认的
        GenerationEntity ge = new GenerationEntity();
        ge.setEntityName(NameUtil.getEntityHumpName(tableName));
        //当前对象所在的包名
        ge.setCodePackage("com.csinc.template");
        ge.setAuthor("kingboy Auto Generate!");
        ge.setCopyright("/**copyright www.csinc.com**/");
        codeGenModel.setGenerationEntity(ge);
        //生成代码
        getTemplate("beetl/backstage/");
        List<String> fileList = new ArrayList<>();
        for (TemplateModel templateModel:templateList) {
            fileList.add(templateModel.getFileModel().getFile());
        }
        codeGenModel.setFileList(fileList);
        outFileList.addAll(CodeGenUtil.codeGen(codeGenModel));
        //将生成的模板输出到本地文件夹
        writeThisFileList(localPath, "UTF-8", outFileList, templateList, ge);
    }

    /**
     * 本地输出代码
     */
    private static void writeThisFileList(String localPath, String encoded, List<String> fileList, List<TemplateModel> templateList, GenerationEntity ge) {
        for (int i = 0; i < fileList.size(); i++) {
            // 文件路径包括 本地项目路径 + 项目相对路径 + 包路径 + 类的自我路径
            String filePath = localPath + File.separator +
                    (StringUtils.isNotEmpty(templateList.get(i).getLocalPath()) ?
                            templateList.get(i).getLocalPath().replaceAll("\\.", "\\/") + File.separator : "") +
                    getPackagePath(templateList.get(i), ge);
            log.info("生成的文件路径是：" + filePath);
            File path = new File(filePath + File.separator);
            if (!path.exists()) {
                path.mkdirs();
            }

            try {
                File file = new File(filePath + File.separator + getFileName(templateList.get(i), ge));
                FileUtils.writeStringToFile(file, fileList.get(i), encoded);
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    private static String getPackagePath(TemplateModel templateModel, GenerationEntity ge) {
        if (templateModel.getFileName().endsWith("js")) {
            return ge.getJsPackage().replaceAll("\\.", "\\/")
                    + (StringUtils.isNotEmpty(templateModel.getTemplatePath()) ? "/"
                    + templateModel.getTemplatePath().replaceAll("\\.", "\\/") : "");
        } else if (templateModel.getFileName().endsWith("html")) {
            return ge.getHtmlPackage().replaceAll("\\.", "\\/")
                    + (StringUtils.isNotEmpty(templateModel.getTemplatePath()) ? "/"
                    + templateModel.getTemplatePath().replaceAll("\\.", "\\/") : "");
        } else if (templateModel.getFileName().endsWith("xml")) {
            return ge.getXmlPackage().replaceAll("\\.", "\\/")
                    + (StringUtils.isNotEmpty(templateModel.getTemplatePath()) ? "/"
                    + templateModel.getTemplatePath().replaceAll("\\.", "\\/") : "");
        } else {
            return ge.getCodePackage().replaceAll("\\.", "\\/")
                    + (StringUtils.isNotEmpty(templateModel.getTemplatePath()) ? "/"
                    + templateModel.getTemplatePath().replaceAll("\\.", "\\/") : "");
        }
    }

    private static String getFileName(TemplateModel templateModel, GenerationEntity ge) {
        if (templateModel.getFileName().endsWith("js")) {
            return String.format(templateModel.getFileName(), ge.getEntityName().toLowerCase());
        } else if (templateModel.getFileName().endsWith("html")) {
            return String.format(templateModel.getFileName(), ge.getEntityName().toLowerCase());
        } else if (templateModel.getFileName().endsWith("xml")) {
            return String.format(templateModel.getFileName(), ge.getEntityName());
        } else {
            return String.format(templateModel.getFileName(), ge.getEntityName());
        }
    }

    private static List<TemplateModel> getTemplate(String path) throws IOException {
        File file = ResourceUtils.getResource(path).getFile();
        List<String> childrenList = FileUtils.findChildrenList(file, false);

        for (String str : childrenList) {
            TemplateModel templateModel = new TemplateModel();
            String[] tmp = str.split("\\.");
            if(tmp[0].equals("ServiceImpl")){
                tmp[0]= "Service.Impl";
            }
            templateModel.setFileName("%s"+str);
            if(tmp[0].equals("Service")){
                templateModel.setFileName("I%s"+str);
            }

            templateModel.setTemplatePath(StringUtils.lowerCase(tmp[0]));
            templateModel.setLocalPath(tmp[1]);
            templateModel.setTemplateType(GenCoreConstant.BEETL);
            templateModel.setTemplateDesc("由代码生成工具生成");
            String tempTemplate=ResourceUtils.getResourceFileContent(path + str);
            TemplateFileModel templateFileModel = new TemplateFileModel();
            templateFileModel.setFile(tempTemplate);
            templateModel.setFileModel(templateFileModel);
//            log.info("读取模板："+templateModel.toString());
            templateList.add(templateModel);
        }
        return templateList;
    }
}
